﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace EntityMetadata
{
    public abstract class DefBase
    {
        protected static bool Getbool(DataRow r, string fieldName)
        {
            bool? b = Getnullablebool(r, fieldName);
            return null == b ? false : true;
        }

        protected static bool? Getnullablebool(DataRow r, string fieldName)
        {
            if (string.IsNullOrEmpty(r[fieldName].ToString()))
            {
                return null;
            }
            else if (r[fieldName].ToString().ToLower() == "true")
            {
                return true;
            }

            return false;
        }

        protected static Nullable<T> GetNullable<T>(DataRow r, string fieldName) where T : struct
        {
            T retVal;
            object value = r[fieldName];

            if (!(value is DBNull) && !string.IsNullOrEmpty(r[fieldName].ToString()))
            {
                try
                {
                    if (typeof(T).Name == typeof(int).Name || typeof(T).Name == typeof(long).Name)
                    {
                        string s = r[fieldName].ToString();
                        object o = (int)Math.Floor(double.Parse(s));
                        retVal = (T)o;
                    }
                    else
                    {
                        retVal = (T)(r[fieldName]);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Invalid value in " + fieldName, ex);
                }

                return retVal;
            }
            else
            {
                return null;
            }
        }

        protected static string Getstring(DataRow r, string fieldName)
        {
            if (r[fieldName] == null)
            {
                return null;
            }
            return r[fieldName].ToString().ToString();
        }

        protected static int Getint(DataRow r, string fieldName)
        {
            int? i = GetNullable<int>(r, fieldName);
            if (null == i)
                return 0;
            else
                return (int)i;
        }

        protected static double Getdouble(DataRow r, string fieldName)
        {
            double? d = Getnullabledouble(r, fieldName);
            return null == d ? (double)0.0 : (double)d;
        }

        protected static double? Getnullabledouble(DataRow r, string fieldName)
        {
            return GetNullable<double>(r, fieldName);
        }

        protected static int? Getnullableint(DataRow r, string fieldName)
        {
            return GetNullable<int>(r, fieldName);
        }
    }
}
